﻿#include "radiatedtestflowsession.h"
#include "common/datatypes.h"
#include "common/common.h"
#include <QThread>
#include <common/calcutils.h>

bool RadiatedFlow::ensureSessionsForSubrange(const Exec::Subrange &subrange,
                                             TestFlowSessionPtr reuseCandidate,
                                             TestFlowSessionPtr &outSession,
                                             TestFlowCallbacks callbacks,
                                             QString &errorMessage)
{
    const void *hardwareKey = subrange.hw ? subrange.hw.data() : nullptr;

    // 若有复用候选且硬件相同，直接复用
    // if (reuseCandidate && reuseCandidate->hardwareKey == hardwareKey) {
    //     outSession = reuseCandidate;
    //     return true;
    // }
    // 否则创建新的会话对象，并根据 subrange.hw 的设备配置进行连接
    auto session = std::make_shared<RadiatedTestFlowSession>();
    session->hardwareKey = hardwareKey;
    if (!subrange.hw) {
        errorMessage = "hw is null";
        return false;
    }

    DeviceMeasureStatus dms;
    dms.stat = DeviceStatus::Connected;
    // 读取信号源配置（只读），并创建设备实例
    if (subrange.hw->gen) {
        const GeneratorConfig &genCfg = *subrange.hw->gen; // 解引用只读指针
        const GeneralAttributes &ga = genCfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &addr = ga.InterfaceAddr;              // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动

        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (dllPath.isEmpty() || dllPathIO.isEmpty()) {
            errorMessage = "Generator open";
            qDebug() << errorMessage;
            qCritical() << QString("No driver DLL for generator or IO model=%1, IO=%2").arg(model).arg(libPath);
            return false;
        }

        // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
        session->generatorIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
        session->generator = makeDeviceHandle<ISignalGenerator>(dllPath);
        if (!session->generator || !session->generatorIO) {
            errorMessage = QString("Create generator or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
            return false;
        }
        session->generator->setDeviceIO(session->generatorIO.get());
        if (!session->generator->connect(addr)) {
            errorMessage = QString("Generator open failed: %1").arg(addr);
            session->closeAll();
            return false;
        }
        if (callbacks.deviceMeasureStatus) {
            dms.role = DeviceRole::SignalGenerator;
            callbacks.deviceMeasureStatus(dms);
        } else {
            errorMessage = QString("callbacks.deviceMeasureStatus config err");
            return false;
        }
    } else {
        errorMessage = QString("Generator config err");
        return false;
    }
    if (subrange.hw->amp) {
        const AmplifierConfig &cfg = *subrange.hw->amp; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &addr = ga.InterfaceAddr;              // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动

        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (dllPath.isEmpty() || dllPathIO.isEmpty()) {
            errorMessage = QString("No driver DLL for Amplifier or IO model=%1, IO=%2").arg(model).arg(libPath);
            session->closeAll();
            return false;
        }

        // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
        session->amplifierIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
        session->amplifier = makeDeviceHandle<IPowerAmplifier>(dllPath);
        if (!session->amplifier || !session->amplifierIO) {
            errorMessage = QString("Create amplifier or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
            session->closeAll();
            return false;
        }
        session->amplifier->setDeviceIO(session->amplifierIO.get());

        if (!session->amplifier->connect(addr)) {
            errorMessage = QString("amplifier open failed: %1").arg(addr);
            session->closeAll();
            return false;
        }
        dms.role = DeviceRole::Amplifier;
        callbacks.deviceMeasureStatus(dms);

    } else {
        errorMessage = QString("Amplifier config err");
        session->closeAll();
        return false;
    }
    if (subrange.hw->fieldProbe) {
        const FieldProbesConfig &cfg = *subrange.hw->fieldProbe; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &addr = ga.InterfaceAddr;              // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动

        monitorDeviceIsFieldProbes = false;
        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
            session->fieldProbeIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
            session->fieldProbe = makeDeviceHandle<IFieldProbe>(dllPath);
            if (!session->fieldProbe || !session->fieldProbeIO) {
                errorMessage = QString("Create fieldProbe or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                session->closeAll();
                return false;
            }
            session->fieldProbe->setDeviceIO(session->fieldProbeIO.get());

            if (!session->fieldProbe->connect(addr)) {
                errorMessage = QString("fieldProbe open failed: %1").arg(addr);
                session->closeAll();
                return false;
            }
            monitorDeviceIsFieldProbes = true;

            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
        }
    }
    QString fwdPmAddr, revPmAddr, monPmAddr;
    if (subrange.hw->fwdPM) {
        const PowerMeterConfig &cfg = *subrange.hw->fwdPM; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举F
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动
        fwdPmAddr = ga.InterfaceAddr;                        // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        session->fwdPowerMeterChannel = (cfg.DeviceChannel == "B") ? 2 : 1;

        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
            // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
            session->forwardPowerMeterIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
            session->forwardPowerMeter = makeDeviceHandle<IPowerMeter>(dllPath);
            if (!session->forwardPowerMeter || !session->forwardPowerMeterIO) {
                errorMessage = QString("Create forwardPowerMeter or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                session->closeAll();
                return false;
            }
            session->forwardPowerMeter->setDeviceIO(session->forwardPowerMeterIO.get());
            if (!session->forwardPowerMeter->connect(fwdPmAddr)) {
                errorMessage = QString("forwardPowerMeter open failed: %1").arg(fwdPmAddr);
                session->closeAll();
                return false;
            }
            session->forwardPowerMeter->reset();
            dms.role = DeviceRole::PowerMeterForward;
            callbacks.deviceMeasureStatus(dms);
        }
    }
    if (subrange.hw->revPM) {
        const PowerMeterConfig &cfg = *subrange.hw->revPM; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动
        revPmAddr = ga.InterfaceAddr;                        // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        session->revPowerMeterChannel = (cfg.DeviceChannel == "B") ? 2 : 1;
        if (revPmAddr == fwdPmAddr && session->forwardPowerMeter) {
            session->reversePowerMeter = session->forwardPowerMeter;
            dms.role = DeviceRole::PowerMeterReverse;
            callbacks.deviceMeasureStatus(dms);
        } else {
            const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
            const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
            if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
                // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
                session->reversePowerMeterIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
                session->reversePowerMeter = makeDeviceHandle<IPowerMeter>(dllPath);
                if (!session->reversePowerMeter || !session->reversePowerMeterIO) {
                    errorMessage = QString("Create reversePowerMeter or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                    session->closeAll();
                    return false;
                }
                session->reversePowerMeter->setDeviceIO(session->reversePowerMeterIO.get());
                if (!session->reversePowerMeter->connect(revPmAddr)) {
                    errorMessage = QString("reversePowerMeter open failed: %1").arg(revPmAddr);
                    session->closeAll();
                    return false;
                }
                session->reversePowerMeter->reset();
                dms.role = DeviceRole::PowerMeterReverse;
                callbacks.deviceMeasureStatus(dms);
            }
        }
    }
    //场强探头连接成功后，表示当前设备为场强而非天线，无需连接监测功率计
    if (subrange.hw->monPM && !monitorDeviceIsFieldProbes) {
        const PowerMeterConfig &cfg = *subrange.hw->monPM; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动
        monPmAddr = ga.InterfaceAddr;                        // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        session->monPowerMeterChannel = (cfg.DeviceChannel == "B") ? 2 : 1;
        if (monPmAddr == fwdPmAddr && session->forwardPowerMeter) {
            session->monitorPowerMeter = session->forwardPowerMeter;
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
        } else if (monPmAddr == revPmAddr && session->reversePowerMeter) {
            session->monitorPowerMeter = session->reversePowerMeter;
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
        } else {
            const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
            const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
            if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
                // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
                session->monitorPowerMeterIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
                session->monitorPowerMeter = makeDeviceHandle<IPowerMeter>(dllPath);
                if (!session->monitorPowerMeter || !session->monitorPowerMeterIO) {
                    errorMessage = QString("Create monitorPowerMeter or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                    session->closeAll();
                    return false;
                }
                session->monitorPowerMeter->setDeviceIO(session->monitorPowerMeterIO.get());

                if (!session->monitorPowerMeter->connect(monPmAddr)) {
                    errorMessage = QString("monitorPowerMeter open failed: %1").arg(monPmAddr);
                    session->closeAll();
                    return false;
                }
                session->monitorPowerMeter->reset();
                dms.role = DeviceRole::PowerMeterMonitor;
                callbacks.deviceMeasureStatus(dms);
            }
        }
    }
    //场强探头连接成功后，表示当前设备为场强而非天线，
    //如果监测功率计连接成功，不再连接接收机。
    if (subrange.hw->monPM->gAttributes.Model == STR_NO_DEVICE && !monitorDeviceIsFieldProbes) {
        const ReceiverConfig &cfg = *subrange.hw->rec; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = ga.type;                  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &addr = ga.InterfaceAddr;              // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动

        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
            // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
            session->receiverIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
            session->receiver = makeDeviceHandle<IReceiver>(dllPath);
            if (!session->receiver || !session->receiverIO) {
                errorMessage = QString("Create receiver or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                session->closeAll();
                return false;
            }
            session->receiver->setDeviceIO(session->receiverIO.get());

            if (!session->receiver->connect(addr)) {
                errorMessage = QString("receiver open failed: %1").arg(addr);
                session->closeAll();
                qCritical() << errorMessage;
                return false;
            }
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
        }
        if (!session->initReceiver(model)) {
            errorMessage = "init receiver fail";
            session->closeAll();
            qCritical() << errorMessage;

            dms.role = DeviceRole::PowerMeterMonitor;
            dms.stat = DeviceStatus::Abnormal;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }

    QSharedPointer<const ConnectorConfig> isSwitch = nullptr;
    if (subrange.hw->c_sig2pa->gAttributes.Model != STR_NO_DEVICE && !subrange.hw->c_sig2pa->gAttributes.InterfaceAddr.isEmpty() && !subrange.hw->c_sig2pa->gAttributes.InterfaceAddr.isEmpty())
        isSwitch = subrange.hw->c_sig2pa;
    else if (subrange.hw->c_fwd2pm->gAttributes.Model != STR_NO_DEVICE && !subrange.hw->c_fwd2pm->gAttributes.InterfaceAddr.isEmpty() && !subrange.hw->c_fwd2pm->gAttributes.InterfaceAddr.isEmpty())
        isSwitch = subrange.hw->c_fwd2pm;
    else if (subrange.hw->c_rev2pm->gAttributes.Model != STR_NO_DEVICE && !subrange.hw->c_rev2pm->gAttributes.InterfaceAddr.isEmpty() && !subrange.hw->c_rev2pm->gAttributes.InterfaceAddr.isEmpty())
        isSwitch = subrange.hw->c_rev2pm;
    else if (subrange.hw->c_pa2tr->gAttributes.Model != STR_NO_DEVICE && !subrange.hw->c_pa2tr->gAttributes.InterfaceAddr.isEmpty() && !subrange.hw->c_pa2tr->gAttributes.InterfaceAddr.isEmpty())
        isSwitch = subrange.hw->c_pa2tr;
    else if (subrange.hw->c_tr2pm->gAttributes.Model != STR_NO_DEVICE && !subrange.hw->c_tr2pm->gAttributes.InterfaceAddr.isEmpty() && !subrange.hw->c_tr2pm->gAttributes.InterfaceAddr.isEmpty())
        isSwitch = subrange.hw->c_tr2pm;

    if (isSwitch && isSwitch->gAttributes.Model != STR_NO_DEVICE) {
        const ConnectorConfig &cfg = *isSwitch; // 解引用只读指针
        const GeneralAttributes &ga = cfg.gAttributes;

        const DeviceType devType = DeviceType::SwitchUnits;  // DeviceType
        const DeviceInterfaceType ifType = ga.InterfaceType; // 枚举
        const QString &addr = ga.InterfaceAddr;              // "TCPIP0::1.2.3.4::5025::SOCKET" 等
        const QString &model = ga.Model;                     // 型号
        const QString &libPath = ga.LibraryPath;             //驱动

        const QString dllPath = Utils::instance()->resolveDriverPath(devType, libPath);
        const QString dllPathIO = Utils::instance()->resolveDriverPathIO(ifType);
        if (model != STR_NO_DEVICE && !dllPath.isEmpty() && !dllPathIO.isEmpty()) {
            // 通过 DeviceInstanceManager 创建实例，交给 DeviceHandle 管理
            session->switchUnitIO = makeDeviceHandle<IDeviceIO>(dllPathIO);
            session->switchUnit = makeDeviceHandle<ISwitchUnit>(dllPath);
            if (!session->switchUnit || !session->switchUnitIO) {
                errorMessage = QString("Create switchUnit or IO instance failed: %1, %2").arg(dllPath).arg(dllPathIO);
                session->closeAll();
                return false;
            }
            session->switchUnit->setDeviceIO(session->switchUnitIO.get());

            if (!session->switchUnit->connect(addr)) {
                errorMessage = QString("switchUnit open failed: %1").arg(addr);
                session->closeAll();
                qCritical() << errorMessage;
                return false;
            }
        }
        bool st = true;
        if (subrange.hw->c_sig2pa->gAttributes.Model != STR_NO_DEVICE && session->switchUnit)
            st &= session->switchUnit->setPath(subrange.hw->c_sig2pa->switchChannel, subrange.hw->c_sig2pa->switchPath);
        if (subrange.hw->c_fwd2pm->gAttributes.Model != STR_NO_DEVICE && session->switchUnit)
            st &= session->switchUnit->setPath(subrange.hw->c_fwd2pm->switchChannel, subrange.hw->c_fwd2pm->switchPath);
        if (subrange.hw->c_rev2pm->gAttributes.Model != STR_NO_DEVICE && session->switchUnit)
            st &= session->switchUnit->setPath(subrange.hw->c_rev2pm->switchChannel, subrange.hw->c_rev2pm->switchPath);
        if (subrange.hw->c_pa2tr->gAttributes.Model != STR_NO_DEVICE && session->switchUnit)
            st &= session->switchUnit->setPath(subrange.hw->c_pa2tr->switchChannel, subrange.hw->c_pa2tr->switchPath);
        if (subrange.hw->c_tr2pm->gAttributes.Model != STR_NO_DEVICE && session->switchUnit)
            st &= session->switchUnit->setPath(subrange.hw->c_tr2pm->switchChannel, subrange.hw->c_tr2pm->switchPath);

        if (!st) {
            errorMessage = "init switchUnit fail";
            session->closeAll();
            qCritical() << errorMessage;
            return false;
        }
    }

    if (!checkConfigurationValidity(subrange, errorMessage))
        return false;

    preInputVal = subrange.hw->gen->LevelMin;
    outSession = std::move(session);
    return true;
}

void RadiatedFlow::safeMuteAllOutputs(const TestFlowSessionPtr &session)
{
    auto radiatedSession = std::dynamic_pointer_cast<RadiatedTestFlowSession>(session);
    if (radiatedSession) {
        radiatedSession->safeMuteAllOutputs();
        radiatedSession->closeAll();
    }
}

bool RadiatedFlow::measureOnePoint(const Exec::Subrange &subrange, int frequencyIndex,
                                   const TestFlowSessionPtr &session, TestFlowCallbacks callbacks, QString &errorMessage)
{
    auto flowSession = std::dynamic_pointer_cast<RadiatedTestFlowSession>(session);
    if (!flowSession) {
        errorMessage = "Invalid session for RadiatedFlow";
        return false;
    }

    if (frequencyIndex < 0 || frequencyIndex >= subrange.freqPoints_Hz.size()) {
        errorMessage = "Frequency index out of range";
        return false;
    }
    // 1) 检查是否请求停止
    if (callbacks.isStopRequested && callbacks.isStopRequested()) {
        errorMessage = "Stopped by user request";
        return true;
    }

    const double frequency_Hz = subrange.freqPoints_Hz[frequencyIndex];
    if (callbacks.logLine)
        callbacks.logLine(QString("setFreq %1 MHz").arg(frequency_Hz / 1e6, 0, 'f', 6));
    else {
        errorMessage = "callbacks.logLine is nullptr!";
        return false;
    }

    if (!flowSession->setFrequency(frequency_Hz, callbacks)) {
        errorMessage = "Failed to set the frequency!";
        return false;
    }
    //设备静默按流程开启
    if (flowSession->rfMuted) {
        if (!flowSession->ensureOutputsEnabled()) {
            errorMessage = "Failed to RF ON";
            return false;
        }
        //调制只需要开启一次，不需要每个频率点都设置。
        if (subrange.modulation == GeneratorModulationType::PM) {
            if (!flowSession->generator->setModulationState(true,1)) {
                errorMessage = "Failed to set the setModulationState!";
                return false;
            }
            if (!flowSession->generator->setPulmState(true,1)) {
                errorMessage = "Failed to set the pulmState!";
                return false;
            }
            if (!flowSession->generator->setPlumPeriod(subrange.plumPeriod)) {
                errorMessage = "Failed to set the setPlumPeriod!";
                return false;
            }
            if (!flowSession->generator->setPlumWidth(subrange.plumWidth)) {
                errorMessage = "Failed to set the setPlumWidth!";
                return false;
            }
        }

        flowSession->rfMuted = false;
    }

    if (frequency_Hz >= (380 * 1e6) && frequency_Hz <= (430 * 1e6)) {
        if (!flowSession->setAmplifierOutput(true)) {
            errorMessage = "Failed to open the amplifier output";
            return false;
        }
    }

    double currentInputVal = preInputVal;
    currentInputVal -= 3;
    if (currentInputVal < subrange.hw->gen->LevelMin)
        currentInputVal = subrange.hw->gen->LevelMin;

    if (!flowSession->setInputLevel(currentInputVal, callbacks)) {
        errorMessage = "Failed to set the generator amplitude!";
        return false;
    }

    QThread::msleep(300);
    double targetVal = subrange.limitCurve->ys[frequencyIndex];
    double precisionGradeUp = subrange.upperTol_dB;   //精度上限 0~2
    double precisionGradeDown = subrange.lowerTol_dB; //精度下限 0~2
    double inputMax = subrange.hw->amp->InputLevelMax;

    double swr = 1;                         //驻波
    double currentImmunityLevel = 0;        //当前干扰电平
    double targetImmunityLevel = targetVal; //目标干扰电平
    double adjustCurrentValue = 0;          //调整当前值
    double adjustTargetValue = 0;           //调整目标值

    double fwdPower = 0;
    double revPower = 0;
    double monValuePower = 0; //监测功率
    double currentFwdPower = 0;
    double currentRevPower = 0;
    double curFwdW = 0;
    double curRevW = 0;

    //使用场强探头时，依据目标场强值targetVal，计算场强上限、下限调整范围值
    /**
      * @brief
      * 第一个参数单位 V/m, 第二个参数单位 dB，返回场强单位
      * 此函数计算  V/m 加减dB单位后，得到的V/m值
    */
    double upImmLevelVm = CalcUtils::dB2Vm(targetVal, precisionGradeUp);
    double fieldPrecisionGradeUp = upImmLevelVm - targetVal;

    double downImmLevelVm = CalcUtils::dB2Vm(targetVal, -1 * precisionGradeDown);
    double fieldPrecisionGradeDown = targetVal - downImmLevelVm;

    bool isOk = false;
    do {
        if (callbacks.isStopRequested && callbacks.isStopRequested()) {
            errorMessage = "Stopped by user request";
            return true;
        }

        DeviceMeasureStatus dms;
        dms.stat = DeviceStatus::Abnormal;
        fwdPower = flowSession->readFwdPower();
        if (fwdPower <= ERROR_VALUE) {
            errorMessage = "Failed to read the forward power!";
            dms.role = DeviceRole::PowerMeterForward;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
        revPower = flowSession->readRevPower();
        if (revPower <= ERROR_VALUE) {
            errorMessage = "Failed to read the reverse power!";
            dms.role = DeviceRole::PowerMeterReverse;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
        currentFwdPower = fwdPower + subrange.con_Fwd2PmAligned->ys[frequencyIndex]
                          + subrange.ampCouplerFwdAligned->ys[frequencyIndex]
                          - subrange.con_amp2TranAligned->ys[frequencyIndex];
        currentRevPower = revPower + subrange.con_Rev2PmAligned->ys[frequencyIndex]
                          + subrange.ampCouplerRevAligned->ys[frequencyIndex]
                          + subrange.con_amp2TranAligned->ys[frequencyIndex];
#if 0
        if ((currentFwdPower < currentRevPower) && !qFuzzyCompare(revPower, 1e36)) {
            errorMessage = QString("fwd:%1, rev:%2").arg(fwdPower).arg(revPower);
            qCritical() << "readPower: fwd:" << fwdPower << ", rev:" << revPower;
            qCritical() << "currentFwdPower: " << currentFwdPower << ", currentRevPower: " << currentRevPower;
            qCritical() << "The reverse power is greater than the forward power, please check whether the device is normal!";
            return false;
        }
#endif
        curFwdW = CalcUtils::dBm2W(currentFwdPower);
        curRevW = CalcUtils::dBm2W(currentRevPower);

        //计算驻波
        // bool ok = false;
        // swr = CalcUtils::calculateSWR(curFwdW, curRevW, &ok, &errorMessage);
        // if (!ok) {
        //     qWarning() << "Calculate  SWR Failed! " << errorMessage << " ,curFwdW:" + QString::number(curFwdW) + ", curRevW: " + QString::number(curRevW);
        //     callbacks.logLine("Calculate SWR Failed!");
        //     swr = 0;
        // }
        double monitorPower_dBm = 0;
        if (options_.stage == TestProcessStage::Testing) {
            if (options_.levelMode == LevelModeType::Sensor) {
                if (!monitorDeviceIsFieldProbes) {
                    //测试--》硬件模板--》功率计 + 天线
                    monitorPower_dBm = flowSession->readMonitorPower();
                    monValuePower = monitorPower_dBm;
                    if (monitorPower_dBm <= ERROR_VALUE) {
                        errorMessage = "Failed to read the monitor power!";
                        dms.role = DeviceRole::PowerMeterMonitor;
                        callbacks.deviceMeasureStatus(dms);
                        return false;
                    }
                    double currentVal = monitorPower_dBm + subrange.con_tran2MonPMAligned->ys[frequencyIndex];
                    double currentFS = 0.0, targetP = 0.0;
                    if (options_.antennaFactor == AntennaFactorType::Horizontal) {
                        currentFS = CalcUtils::dBm2Vm_general(currentVal, subrange.antHFactorsAligned->ys[frequencyIndex], options_.impedanceOhm); //天线因子 H
                        targetP = CalcUtils::vm2dBm_general(targetVal, subrange.antHFactorsAligned->ys[frequencyIndex], options_.impedanceOhm);
                    } else {
                        currentFS = CalcUtils::dBm2Vm_general(currentVal, subrange.antVFactorsAligned->ys[frequencyIndex], options_.impedanceOhm); //天线因子 H
                        targetP = CalcUtils::vm2dBm_general(targetVal, subrange.antVFactorsAligned->ys[frequencyIndex], options_.impedanceOhm);
                    }
                    currentImmunityLevel = currentFS;
                    adjustCurrentValue = currentVal;
                    adjustTargetValue = targetP;
                } else {
                    //测试--》硬件模板--》场强探头
                    double fieldPower = flowSession->readFieldPower();
                    monValuePower = fieldPower;
                    callbacks.logLine(QString("readField: %1V/m").arg(fieldPower));
                    qDebug() << "read Total Field :" << fieldPower << "V/m";
                    if (fieldPower < 0) {
                        errorMessage = "Failed to read the field power!";
                        dms.role = DeviceRole::PowerMeterMonitor;
                        callbacks.deviceMeasureStatus(dms);
                        return false;
                    }

                    double currentVal = fieldPower * subrange.probeCorrAligned->ys[frequencyIndex];

                    precisionGradeUp = fieldPrecisionGradeUp;
                    precisionGradeDown = fieldPrecisionGradeDown;
                    qDebug() << "precisionGradeUp(V/m): " << precisionGradeUp << " , down: " << precisionGradeDown;
                    currentImmunityLevel = currentVal;
                    adjustCurrentValue = currentVal;
                    adjustTargetValue = targetVal;
                }
            } else if (options_.levelMode == LevelModeType::SubstitutionMethod) {
                //测试--》替代法
                Exec::CalPoint calPoint;
                if (!Utils::findCalibrationDataByFrequency(subrange.cal, frequency_Hz, calPoint)) {
                    errorMessage = "not fond cal data, freq: " + QString::number(frequency_Hz);
                    return false;
                }
                double delta;
                if (options_.powerMeasurement == PowerMeasurementType::Forwrd_Power) {
                    //目标正向功率 = 校准正向功率 + delta;
                    double targetFwdPower;
                    //通过单位判断是否使用净功率方法
                    if (options_.immunityUnit == "W") {
                        /************* 净功率 *****************/
                        double limitVal = CalcUtils::W2dBm(targetVal);
                        double calVal = CalcUtils::W2dBm(calPoint.immunityLevel);
                        delta = limitVal - calVal;
                        //目标正向功率 = 校准正向功率 + delta;
                        targetFwdPower = calPoint.fwd_dBm + delta;
                        //当前净功率W = 当前正向功率 W - 校准反向功率 W
                        currentImmunityLevel = curFwdW - CalcUtils::dBm2W(calPoint.rev_dBm);
                    } else {
                        /************* 前向功率 *****************/
                        /**
                          * @brief Utils::MathUtils::vm2dB(V/m , V/m)
                          * 第一个参数单位 V/m, 第二个参数单位 V/m，返回 dB
                          * 计算两个参数之间相差多少dB
                          */
                        delta = CalcUtils::vm2dB(calPoint.immunityLevel, targetVal);
                        //计算目标正向功率
                        targetFwdPower = calPoint.fwd_dBm + delta;

                        //计算实时正向功率与校准正向功率之间的差 单位dB
                        double realFwdPowerDelta = currentFwdPower - calPoint.fwd_dBm;
                        /**
                          * @brief Utils::MathUtils::dB2Vm()
                          * 第一个参数单位 V/m, 第二个参数单位 dB，返回场强单位
                          * 此函数计算  V/m 加减dB单位后，得到的V/m值
                          */
                        currentImmunityLevel = CalcUtils::dB2Vm(calPoint.immunityLevel, realFwdPowerDelta);
                    }
                    adjustCurrentValue = currentFwdPower;
                    adjustTargetValue = targetFwdPower;
                } else if (options_.powerMeasurement == PowerMeasurementType::Generator_Level) {
                    //发生器电平
                    //计算 delta值
                    delta = CalcUtils::vm2dB(calPoint.immunityLevel, targetVal);
                    double targetSignalOutput = calPoint.amplitude_dBm + delta;

                    currentInputVal = targetSignalOutput;
                    if (!flowSession->setInputLevel(currentInputVal, callbacks)) {
                        errorMessage = "Failed to set the input level!";
                        return false;
                    }
                    currentImmunityLevel = targetVal;
                    targetImmunityLevel = targetVal;
                } else {
                    errorMessage = "config error! PowerMeasurement selection error!";
                    return false;
                }
            }
        } else if (options_.stage == TestProcessStage::Calibration) {
            /***************** 校准 ************************/
            //功率测量模式=净功率,净功率时只能使用W,不能使用V/m单位,因为净功率替代法后面没有监测设备
            if (options_.powerMeasurement == PowerMeasurementType::Net_Power) {
                //保存正向功率,反向功率,净功率;
                //净功率= 正向功率(W)-反向功率(W),显示单位为 W
                double currentW = curFwdW - curRevW;
                double currentNetPowerdBm = CalcUtils::W2dBm(currentW);
                double targetdBm = CalcUtils::W2dBm(targetVal);

                //界面显示单位 W
                currentImmunityLevel = currentW;

                //数据调整单位dBm
                adjustCurrentValue = currentNetPowerdBm;
                adjustTargetValue = targetdBm;
            } else {
                if (!monitorDeviceIsFieldProbes) {
                    //校准--》 硬件模板-》功率计 + 天线
                    monitorPower_dBm = flowSession->readMonitorPower();
                    monValuePower = monitorPower_dBm;
                    if (monitorPower_dBm <= ERROR_VALUE) {
                        errorMessage = "Failed to read the monitor power!";
                        dms.role = DeviceRole::PowerMeterMonitor;
                        callbacks.deviceMeasureStatus(dms);
                        return false;
                    }
                    double currentVal = monitorPower_dBm + subrange.con_tran2MonPMAligned->ys[frequencyIndex];
                    double ImmunityLevel = 0.0, targetP = 0.0;
                    if (options_.antennaFactor == AntennaFactorType::Horizontal) {
                        ImmunityLevel = CalcUtils::dBm2Vm_general(currentVal, subrange.antHFactorsAligned->ys[frequencyIndex], options_.impedanceOhm); //天线因子
                        targetP = CalcUtils::vm2dBm_general(targetVal, subrange.antHFactorsAligned->ys[frequencyIndex], options_.impedanceOhm);
                    } else {
                        ImmunityLevel = CalcUtils::dBm2Vm_general(currentVal, subrange.antVFactorsAligned->ys[frequencyIndex], options_.impedanceOhm); //天线因子
                        targetP = CalcUtils::vm2dBm_general(targetVal, subrange.antVFactorsAligned->ys[frequencyIndex], options_.impedanceOhm);
                    }
                    currentImmunityLevel = ImmunityLevel;
                    adjustCurrentValue = currentVal;
                    adjustTargetValue = targetP;
                } else {
                    //校准--》硬件模板-》探头
                    double fieldPower = flowSession->readFieldPower();
                    monValuePower = fieldPower;
                    callbacks.logLine(QString("readField: %1V/m").arg(fieldPower));
                    if (fieldPower < 0) {
                        errorMessage = "Failed to read the field power!";
                        dms.role = DeviceRole::PowerMeterMonitor;
                        callbacks.deviceMeasureStatus(dms);
                        return false;
                    }
                    double currentVal = fieldPower * subrange.probeCorrAligned->ys[frequencyIndex];
                    precisionGradeUp = fieldPrecisionGradeUp;
                    precisionGradeDown = fieldPrecisionGradeDown;
                    qDebug() << "precisionGradeUp(V/m): " << precisionGradeUp << " , down: " << precisionGradeDown;
                    callbacks.logLine(QString("Up(V/m): %1 , down: %2").arg(precisionGradeUp).arg(precisionGradeDown));
                    currentImmunityLevel = currentVal;
                    adjustCurrentValue = currentVal;
                    adjustTargetValue = targetVal;
                }
            }
        }

        QString info = QString("read Power, fwdPower: %1(dBm), revPower: %2(dBm), monPower: %3(Vm/dBm)").arg(fwdPower).arg(revPower).arg(monValuePower);
        qInfo() << info;
        callbacks.logLine(info);
        qDebug() << "Generator current Amplitude: " << currentInputVal;
        qDebug() << "Coupler Power(dBm), currentFwdPower:" << QString::number(currentFwdPower) << " currentRevPower: " << QString::number(currentRevPower);
        qDebug() << QString("currentImmunityLevel(%1): ").arg(options_.immunityUnit) << currentImmunityLevel << ", targetImmunityLevel: " << targetImmunityLevel;
        qInfo() << "adjustCurrentValue : " << adjustCurrentValue << ", adjustTargetValue: " << adjustTargetValue << endl;
        info = QString("adjustCurrentValue : %1, adjustTargetValue: %2 \r\n").arg(adjustCurrentValue).arg(adjustTargetValue);
        callbacks.logLine(info);

        // 刷新测量进度
        if (callbacks.progress) {
            MeasurementPoint point;
            point.calTable.Freq = frequency_Hz;                                       //MHz
            point.calTable.Amplitude = currentInputVal;                               //幅度
            point.calTable.FwdPower = currentFwdPower;                                //正向功率
            point.calTable.RevPower = currentRevPower;                                //反向功率
            point.calTable.ImmunityLevelUnit = options_.immunityUnit;                 //抗干扰等级单位
            point.calTable.ImmunityLevel = currentImmunityLevel;                      //实际抗干扰等级
            point.calTable.LimitImmunityLevel = targetImmunityLevel;                  //限值(额定干扰等级)
            point.calTable.swr = swr;                                                 //驻波比
            point.calTable.Loss = subrange.con_tran2MonPMAligned->ys[frequencyIndex]; //衰减补偿
            point.calTable.CloseLoop = false;                                         //是否闭环调试过
            point.calTable.info = "";                                                 //(频段、步进模式、LNE值、LOG值、驻留时间、调制方式）
            callbacks.progress(point);
        }

        //发生器电平测试，不需要调整
        if (options_.stage == TestProcessStage::Testing
            && options_.levelMode == LevelModeType::SubstitutionMethod
            && options_.powerMeasurement == PowerMeasurementType::Generator_Level) {
            isOk = true;
            break;
        }

        int ret = adjust(currentInputVal, adjustCurrentValue, adjustTargetValue, precisionGradeUp, precisionGradeDown,
                         subrange.hw->gen->LevelMin, subrange.hw->gen->LevelMax, inputMax, errorMessage);

        if (ret == -1) {
            return false;
        } else if (ret == 1) {
            preInputVal = currentInputVal;
            if (options_.stage == TestProcessStage::Testing)
                QThread::msleep(static_cast<unsigned long>(subrange.dwell_ms));
            isOk = true;
            break;
        }
        if (!flowSession->setInputLevel(currentInputVal, callbacks)) {
            errorMessage = "Failed to set the generator amplitude!";
            return false;
        }

        // 检查是否请求停止
        if (callbacks.isStopRequested && callbacks.isStopRequested()) {
            //            errorMessage = "Stopped by user request";
            return false;
        }
        QThread::msleep(300);

    } while (!isOk);
    return true;
}

void RadiatedFlow::setPlanOptions(const FlowPlanOptions &opts)
{
    options_ = opts;
}

bool RadiatedFlow::checkConfigurationValidity(const Exec::Subrange &subrange, QString &errorMessage)
{
    //监测天线，检查天线因子单位和个数
    if (!monitorDeviceIsFieldProbes) {
        bool isValid = true;
        if (options_.antennaFactor == AntennaFactorType::Vertical) {
            if (!subrange.antVFactorsAligned || subrange.antVFactorsAligned->ys.size() != subrange.freqPoints_Hz.size()
                || subrange.antVFactorsAligned->sourceUnit != STR_UNIT_DBM
                || subrange.antVFactorsAligned->targetUnit != STR_UNIT_VM)
                isValid = false;
        } else {
            if (!subrange.antHFactorsAligned || subrange.antHFactorsAligned->ys.size() != subrange.freqPoints_Hz.size()
                || subrange.antHFactorsAligned->sourceUnit != STR_UNIT_DBM
                || subrange.antHFactorsAligned->targetUnit != STR_UNIT_VM)
                isValid = false;
        }
        if (!isValid) {
            errorMessage = "Antenna factor data error";
            qCritical() << errorMessage;
            if (subrange.antVFactorsAligned)
                qInfo() << "VFactor size:" << subrange.antVFactorsAligned->ys.size() << ", SourceUnit:" << subrange.antVFactorsAligned->sourceUnit << ", TargetUnit:" << subrange.antVFactorsAligned->targetUnit;
            if (subrange.antHFactorsAligned)
                qInfo() << "HFactor size:" << subrange.antHFactorsAligned->ys.size() << ", SourceUnit:" << subrange.antHFactorsAligned->sourceUnit << ", TargetUnit:" << subrange.antHFactorsAligned->targetUnit;
            return false;
        }
    }
    if (options_.stage == TestProcessStage::Testing) {
        if (options_.powerMeasurement == PowerMeasurementType::Net_Power) {
            errorMessage = " No relevant testing process was found!";
            return false;
        }
        //探头法，发生器电平测试单位是 应该是V/m、dBuA,不能是W
        if (options_.levelMode == LevelModeType::Sensor || options_.powerMeasurement == PowerMeasurementType::Generator_Level) {
            if (options_.immunityUnit == "W") {
                errorMessage = "The current configured test method Immunity level unit cannot be < W > !";
                return false;
            }
        }
        //替代法
        if (options_.levelMode == LevelModeType::SubstitutionMethod) {
            if (!subrange.cal || subrange.cal->size() < subrange.freqPoints_Hz.size()) {
                errorMessage = "Cal data or Freq points error! ";
                qCritical() << errorMessage << "cal.size:" << subrange.cal->size() << ", testFreqs: " << subrange.freqPoints_Hz;
                return false;
            }
            if (subrange.cal->first().immunityUnit != options_.immunityUnit) {
                qWarning() << "CalData ImmunityLevelUnit :" << subrange.cal->first().immunityUnit;
                qWarning() << "Current config ImmunityLevelUnit  :" << options_.immunityUnit;
                errorMessage = "Calibration data immunity level unit does not match the current test!";
                return false;
            }
        }
    } else if (options_.stage == TestProcessStage::Calibration) {
        if (options_.levelMode == LevelModeType::Sensor) {
            errorMessage = "No relevant calibration process was found!";
            return false;
        }
        if (options_.powerMeasurement == PowerMeasurementType::Net_Power) {
            if (options_.immunityUnit != "W") {
                errorMessage = "Net power test immunity level unit must be < W >!";
                return false;
            }
        } else {
            if (options_.immunityUnit == "W") {
                errorMessage = "The current configured test method Immunity level unit cannot be < W > !";
                return false;
            }
        }
    }
    return true;
}

void RadiatedTestFlowSession::safeMuteAllOutputs()
{
    if (generator) {
        //保护功放措施
        if (!generator->setAmplitude(-50))
            qWarning() << "generator setOutput 0 error";

        if (!generator->setModulationState(false,1))
            qWarning() << "Failed to set the setModulationState!";
        if (!generator->setPulmState(false,1))
            qWarning() << "Failed to set the pulmState!";
        if (!generator->setOutput(false))
            qWarning() << "generator setOutput 0 error";
    }
    if (amplifier) {
        if (!amplifier->setOutput(false))
            qWarning() << "PA setOutput 0 error";
    }
    rfMuted = true;
}

bool RadiatedTestFlowSession::ensureOutputsEnabled()
{
    if (!amplifier || !generator)
        return false;
    if (amplifier) {
        if (!amplifier->setOutput(true)) {
            qCritical() << "Failed to open the amplifier output";
            return false;
        }
    }

    QThread::msleep(300);
    if (generator) {
        if (!generator->setOutput(true)) {
            qCritical() << "Failed to open the Generator output";
            return false;
        }
    }
    rfMuted = false;
    return true;
}

bool RadiatedTestFlowSession::initReceiver(const QString &mode)
{
    bool isRec = (receiver) ? true : false;
    if (isRec) {
        if (isRec) {
            QString inst = "SA";
            if (mode.contains("RS"))
                inst = "SAN";

            if (!receiver->reset())
                return false;
            if (!receiver->setInstrumentSelect(inst))
                return false;

            QThread::msleep(3000);
        }
        if (!receiver->setInitiateContinuousState(1))
            return false;

        if (!receiver->restart())
            return false;

        if (!receiver->setPowerUnit("DBM"))
            return false;
        if (!receiver->setReferenceLevel(10))
            return false;
    }
    return isRec & true;
}

bool RadiatedTestFlowSession::setAmplifierOutput(bool st)
{
    if (amplifier)
        return amplifier->setOutput(st);
    qCritical() << "setAmplifierOutput err!";
    return false;
}

bool RadiatedTestFlowSession::setGeneratorOutput(bool st)
{
    if (generator)
        return generator->setOutput(st);
    qCritical() << "  setGeneratorOutput err!";
    return false;
}

bool RadiatedTestFlowSession::setFrequency(double freq, const TestFlowCallbacks &callbacks)
{
    if (!amplifier || !generator)
        return false;
    qInfo() << "setFrequency: " << freq;
    DeviceMeasureStatus dms;
    dms.stat = DeviceStatus::Abnormal;
    if (amplifier) {
        if (!amplifier->setFrequency(freq)) {
            qCritical() << " amplifier->setFrequency err!";
            dms.role = DeviceRole::Amplifier;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    if (generator) {
        if (!generator->setFrequency(freq)) {
            qCritical() << " generator->setFrequency err!";
            dms.role = DeviceRole::SignalGenerator;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    if (monitorPowerMeter) {
        if (!monitorPowerMeter->setFrequency(freq, monPowerMeterChannel)) {
            qCritical() << " monitorPowerMeter->setFrequency err!";
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);

            return false;
        }
    }
    if (reversePowerMeter) {
        if (!reversePowerMeter->setFrequency(freq, revPowerMeterChannel)) {
            qCritical() << " reversePowerMeter->setFrequency err!";
            dms.role = DeviceRole::PowerMeterReverse;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    if (forwardPowerMeter) {
        if (!forwardPowerMeter->setFrequency(freq, fwdPowerMeterChannel)) {
            qCritical() << " forwardPowerMeter->setFrequency err!";
            dms.role = DeviceRole::PowerMeterForward;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    if (fieldProbe) {
        if (!fieldProbe->setFrequency(freq)) {
            qCritical() << " fieldProbe->setFrequency err!";
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    if (receiver) {
        if (!receiver->setFrequencyCenter(freq)) {
            qCritical() << "receiver->setFrequencyCenter err!";
            dms.role = DeviceRole::PowerMeterMonitor;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    return true;
}

bool RadiatedTestFlowSession::setInputLevel(double level, const TestFlowCallbacks &callbacks)
{
    if (generator) {
        if (!generator->setAmplitude(level)) {
            qCritical() << " generator->setAmplitude err!";
            DeviceMeasureStatus dms;
            dms.stat = DeviceStatus::Abnormal;
            dms.role = DeviceRole::SignalGenerator;
            callbacks.deviceMeasureStatus(dms);
            return false;
        }
    }
    return true;
}

double RadiatedTestFlowSession::readFwdPower(const QString &arg)
{
    if (forwardPowerMeter)
        return forwardPowerMeter->readPower(fwdPowerMeterChannel, arg);

    return ERROR_VALUE;
}

double RadiatedTestFlowSession::readRevPower(const QString &arg)
{
    if (reversePowerMeter) {
        double val = reversePowerMeter->readPower(revPowerMeterChannel, arg);
        return val;
    }

    return ERROR_VALUE;
}

double RadiatedTestFlowSession::readMonitorPower(const QString &arg)
{
    if (monitorPowerMeter)
        return monitorPowerMeter->readPower(monPowerMeterChannel, arg);
    else if (receiver) {
        double att = receiver->powerAttenuation();
        if (!receiver->calculateMarkerMax(1)) {
            qCritical() << "receiver->calculateMarkerMax err";
            return ERROR_VALUE;
        }
        double val = receiver->calculateMarkerValue(1);
        return val + att;
    }
    return ERROR_VALUE;
}

double RadiatedTestFlowSession::readFieldPower()
{
    if (fieldProbe)
        return fieldProbe->readTotalField();
    return ERROR_VALUE;
}

void RadiatedTestFlowSession::closeAll()
{
    safeMuteAllOutputs();
    closeAndResetAll(
        switchUnit,
        fieldProbe,
        receiver,
        monitorPowerMeter,
        reversePowerMeter,
        forwardPowerMeter,
        amplifier,
        generator);

    resetAll(
        switchUnitIO,
        fieldProbeIO,
        receiverIO,
        monitorPowerMeterIO,
        reversePowerMeterIO,
        forwardPowerMeterIO,
        amplifierIO,
        generatorIO);
}
//-1 有异常  0 正常执行，但未调整到位  1 调整到位
int RadiatedFlow::adjust(double &currentInputVal, double currentVal, double targetVal, double precisionGradeUp, double precisionGradeDown, double levelMin, double levelMax, double inputMax, QString &errorMessage)
{
    //无限循环
    static bool isEndlessLoop = false;
    //循环次数
    static int endlessLoopCount = 0;

    double interval = qAbs(currentVal - targetVal);
    //超过上限
    if (currentVal > targetVal + precisionGradeUp) {
        if ((interval < 0.5) && (currentInputVal - interval < levelMin)) {
            if (interval > 0.001)
                interval = qAbs(currentInputVal - levelMin) / 2;
        }
        currentInputVal -= interval / 2;

        if (isEndlessLoop) {
            isEndlessLoop = false;
            endlessLoopCount++;
            //20次退出
            if (endlessLoopCount > 20) {
                endlessLoopCount = 0;
                errorMessage = QObject::tr("Adjust exceed limit");
                qCritical() << QObject::tr("Unable to adjust to target value!");
                return -1;
            }
        }

        //以当前信号幅度测试
        if (abs(currentInputVal - levelMin) <= 0.0001) {
            currentInputVal = levelMin;
            return 0;
        }

        // 超过输入设备限值，保存数据，测量下一个点
        if (currentInputVal < levelMin) {
            isEndlessLoop = false;
            endlessLoopCount = 0;
            return 1;
        }
    } else if (currentVal < targetVal - precisionGradeDown) {
        //低于下限
        if ((interval < 0.5) && (currentInputVal + interval > levelMax)) {
            if (interval > 0.001)
                interval = qAbs(currentInputVal - levelMin);
        }
        interval = interval / 2;
        if (interval >= 1) {
            interval = 1;
        } else if (interval < 0.001) {
            interval = 0.001;
        }
        currentInputVal += interval;
        isEndlessLoop = true;

        //超过设备限值时，以设备最大输入电平进行测试，并保存。然后测量下一个频率点，不再进行限值报错退出。
        if (abs(currentInputVal - levelMax) <= 0.0001) {
            currentInputVal = levelMax;
            return 0;
        }
        if (abs(currentInputVal - inputMax) <= 0.0001) {
            currentInputVal = inputMax;
            return 0;
        }

        // 超过输入设备限值，保存数据，测量下一个点
        if (currentInputVal > levelMax || currentInputVal > inputMax) {
            isEndlessLoop = false;
            endlessLoopCount = 0;
            return 1;
        }
    } else {
        isEndlessLoop = false;
        endlessLoopCount = 0;
        return 1;
    }
    return 0;
}
